import { Button, Card, Modal, Popover, Space, message } from "antd";
import { useEffect, useState } from "react";
import CodeEditor from '@uiw/react-textarea-code-editor';
import { MoreOutlined } from "@ant-design/icons";
import { getCollectionApi, getToken } from "../utils/client";

export interface DocProps {
    curClientId: string;
    curDatabase: string;
    curCollection: string;
    doc: string;
    onChange: () => void;
}

function Doc(props: DocProps) {
    const [doc, setDoc] = useState("");
    const [inEdit, setInEdit] = useState(false);
    const [hasChange, setHasChange] = useState(false);
    const [showRemoveModal, setShowRemoveModal] = useState(false);

    const getDocId = () => {
        const obj = JSON.parse(props.doc);
        return JSON.stringify({ "_id": obj["_id"] });
    };

    const removeDoc = async () => {
        const client = getCollectionApi();
        try {
            await client.collectionDeletePost({
                collectionDeletePostRequest: {
                    token: getToken(),
                    id: props.curClientId,
                    database: props.curDatabase,
                    collection: props.curCollection,
                    query: getDocId(),
                },
            });
            setShowRemoveModal(false);
            props.onChange();
        } catch (e) {
            console.log(e);
            message.error("删除记录失败，请确认账号权限");
        }
    };

    const updateDoc = async () => {
        let newDoc = "";
        try {
            const obj = JSON.parse(doc);
            const newId = JSON.stringify({ "_id": obj["_id"] });
            if (newId !== getDocId()) {
                message.error("_id发生了变化");
                return;
            }
            newDoc = JSON.stringify(obj);
        } catch (e) {
            console.log(e);
            message.error("不是合法的JSON结构");
        }
        const client = getCollectionApi();
        try {
            await client.collectionUpdatePost({
                collectionInsertPostRequest: {
                    token: getToken(),
                    id: props.curClientId,
                    database: props.curDatabase,
                    collection: props.curCollection,
                    doc: newDoc,
                },
            });
            props.onChange();
            setInEdit(false);
            setHasChange(false);
            message.info("更新成功");
        } catch (e) {
            console.log(e);
            message.error("更新记录失败，请确认账号权限");
        }
    }

    useEffect(() => {
        const obj = JSON.parse(props.doc);
        setDoc(JSON.stringify(obj, null, 2));
    }, [props.doc]);

    return (
        <Card style={{ width: "100%" }} extra={
            <>
                {inEdit == false && (
                    <Space size="middle">
                        <Button type="primary" onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setInEdit(true);
                        }}>修改</Button>
                        <Popover trigger="click" placement="bottom" content={
                            <div>
                                <Button type="link" danger onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setShowRemoveModal(true);
                                }}>删除</Button>
                            </div>
                        }>
                            <MoreOutlined />
                        </Popover>
                    </Space>
                )}
                {inEdit == true && (
                    <Space size="middle">
                        <Button onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            const obj = JSON.parse(props.doc);
                            setDoc(JSON.stringify(obj, null, 2));
                            setHasChange(false);
                            setInEdit(false);
                        }}>取消</Button>
                        <Button type="primary" disabled={!hasChange} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            updateDoc();
                        }}>更新</Button>
                    </Space>
                )}
            </>
        }>
            <CodeEditor
                value={doc}
                language="json"
                minHeight={200}
                readOnly={!inEdit}
                placeholder="请输入代码"
                onChange={(e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    setDoc(e.target.value);
                    setHasChange(true);
                }}
                style={{
                    fontSize: 14,
                    backgroundColor: '#f5f5f5',
                }}
            />
            {showRemoveModal == true && (
                <Modal open title="删除记录"
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowRemoveModal(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeDoc();
                    }}>
                    是否删除记录 {getDocId()} ?
                </Modal>
            )}
        </Card>
    );
}

export default Doc;